package cn.cjxy.controller;

import cn.cjxy.service.IStudentService;
import cn.cjxy.service.impl.StudentServiceImpl;
import cn.cjxy.util.R;
import cn.cjxy.domain.Student;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/student")
@RestController
public class StudentController {
    //用于缓存学生信息
    private static Map<Long, Student> studentCacheMap=new HashMap<>();

    //注入service层
    private IStudentService studentService=new StudentServiceImpl();



    /**
     * 新增用户
     * @param student 用户对象
     * @return
     */
    @PostMapping
    public R<Void> insert(@RequestBody Student student) {
        //1.将学生对象存储到本地缓存
        studentCacheMap.put(student.getId(), student);
        //响应成功
        return R.ok();
    }

    /**
     * 根据id获取学生信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Student> get(@PathVariable Long id) {
        //通过id获取学生对象
        Student student = studentCacheMap.get(id);
        //响应成功携带学生信息
        return R.ok(student);
    }

    /**
     * 查询所有学生
     * @return
     */
    @GetMapping
    public R<List<Student>> getAll() {
        //得到所有学员信息
       List<Student> students = studentCacheMap.keySet()//拿到所有键的集合
                .stream().map(id -> studentCacheMap.get(id))//将id依次取出并使用原map去取值
                .collect(Collectors.toList());

         return R.ok(students);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R<Void> delete(@PathVariable Long id) {
        //从map中移除
        studentCacheMap.remove(id);
        return R.ok();
    }


    /**
     * 修改学生信息
      * @param student
     * @return
     */
    @PutMapping
    public R<Void> update(@RequestBody Student student) {
        //得到已有的学生对象
        //根据id去查询
        Long id = student.getId();
        Student student1 = studentCacheMap.get(id);

        //执行修改
        student1.setName(student.getName());
        student1.setAge(student.getAge());
        student1.setSex(student.getSex());
        studentCacheMap.put(id, student1);

        //响应成功
        return R.ok();
    }

}
